
import {timer as observableTimer} from 'rxjs';
import {Component, ViewChild, AfterViewInit} from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import {FormlyFieldConfig, FormlyFormOptions} from '@ngx-formly/core';
import {ApesContainerComponent} from '../../../shared/apes/container/apes-container.component';
import { AreaService } from '@core/services/masterdata/area.service';
import { catchError, debounceTime, distinctUntilChanged, map, mergeMap, switchMap, tap } from 'rxjs/operators';
import { Observable } from 'rxjs/internal/Observable';
import { Subject } from 'rxjs/internal/Subject';
import { concat } from 'rxjs/internal/observable/concat';
import { of } from 'rxjs/internal/observable/of';
import { ApiService } from '@core/services/http/api.service';
import { missing } from '../../../utils/utils';

@Component({
    selector: 'apes-demo2',
    templateUrl: './demo02.component.html',
    styles: []
})
export class Demo02Component  implements AfterViewInit {

    @ViewChild("cont",{static:false}) cont: ApesContainerComponent;



    form = new FormGroup({'city':new FormControl({ "parent": "340000", "name": "蚌埠市", "id": "340300"}),
    'select1':new FormControl()});


    constructor(private cityService:AreaService,private  apiService:ApiService){
      this.loadContract();
    }
    model: any = {};
    options: FormlyFormOptions = {};
    feild1: FormlyFieldConfig[] = [{
        key: 'name',
        type: 'city-picker',
        templateOptions: {
            label: '注册地',
            placeholder: 'Enter email',
            required: true,
            divCol: 24,
            lblCol: 2,
            level:'district',
            inputCol: 22
        }
    }, {
        key: 'gsid',
        type: 'input',
        templateOptions: {
            label: '公司代码',
            placeholder: '请输入合同名称',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        }
    }, {
        key: 'gsmc',
        type: 'input',
        templateOptions: {
            label: '公司名称',
            placeholder: '请输入公司名称',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        }
    }, {
        key: 'bmmc',
        type: 'input',
        templateOptions: {
            label: '部门名称',
            placeholder: '请输入部门名称',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        }
    }, {
        key: 'startDate',
        type: 'date',
        templateOptions: {
            label: '开始时间',
            placeholder: '结束时间',
            required: true,

        }
    }];

    feild2: FormlyFieldConfig[] = [{
        key: 'khid',
        type: 'input',
        templateOptions: {
            label: '客户姓名',
            placeholder: 'Enter khid',
            required: true,
            divCol: 24,
            lblCol: 2,
            inputCol: 22,
        }
    }, {
        key: 'khmc',
        type: 'input',
        templateOptions: {
            label: '客户名称',
            placeholder: '请输入客户名称',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        }
    }, {
        key: 'hymc',
        type: 'textarea',
        templateOptions: {
            label: '会员名称',
            placeholder: '请输入会员名称',
            required: true,
            divCol: 16,
            lblCol: 4,
            inputCol: 20
        }
    }, {
        key: 'xszzmc',
        type: 'input',
        templateOptions: {
            label: '销售组织名称',
            placeholder: '请输入销售组织名称',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        }
    }, {
        key: 'ip',
        type: 'input',
        templateOptions: {
            label: 'IP Address (pattern = /(\d{1,3}\.){3}\d{1,3}/)',
            pattern: /(\d{1,3}\.){3}\d{1,3}/,
            required: true,
            divCol: 24,
            lblCol: 2,
            inputCol: 22,
            keyup: function () {
                console.log('abc');
            }
        },
        validation: {
            messages: {
                pattern: (error, field: FormlyFieldConfig) => `"${field.formControl.value}" 不是一个有效得IP地址`,
            },
        },
    }, {
        key: 'marvel3',
        type: 'select',
        templateOptions: {
            label: '选择 name/value/group',
            // selectMode: "multiple",
            options: [],
            change: () => {
                console.log('点击事件');
            },
            divCol: 8,
            lblCol: 6,
            inputCol: 18
        },
        lifecycle: {
            onInit: (form, field) => {
                observableTimer(10000).subscribe(() => {
                    field.templateOptions.options = [
                        {label: 'Iron Man', id: 'iron_man', name :"aaa", test: "uuuu"},
                        {label: 'Captain America', id: 'captain_america', name :"bbb"},
                        {label: 'Black Widow', id: 'black_widow', name :"ccc", disabled: true},
                        {label: 'Hulk', id: 'hulk', name :"ddd"},
                        {label: 'Captain Marvel', id: 'captain_marvel', name :"fff"},
                    ];
                });
            }
        }

    }, {
        key: 'hobby',
        type: 'checkbox',
        templateOptions: {
            label: '接收通知',
            title: '是',
            required: true,
            divCol: 8,
            lblCol: 6,
            inputCol: 18,
            click: () => {
                console.log('点击事件');
            }
        }
    }, {
        key: 'multicheckbox',
        type: 'multicheckbox',
        templateOptions: {
            label: '购买的险种',
            options : [
                {label: '划痕险', key: 'iron_man', vaule: 'iron_man', name: 'insurance1'},
                {label: '自燃险', key: 'captain_america', vaule: 'captain_america', name: 'insurance2'},
                {label: '第三者险', key: 'black_widow', vaule: 'black_widow', name: 'insurance3', disabled: true},
                {label: '玻璃险', key: 'hulk', vaule: 'hulk', name: 'insurance4'},
                {label: '第三者不急免赔', key: 'captain_marvel', vaule: 'captain_marvel', name: 'insurance5'}
            ],
            required: true,
            divCol: 24,
            lblCol: 2,
            inputCol: 22,
        }
    }];
    data1 = {
    renderData: [
      {
        col: 12,
        id: "c",
        type: "panel",
        title: "人员信息",
        genre: "form",
        fields: [
          {
            key: 'avc',
            type: 'input',
            templateOptions: {
              label: '公司代码',
              placeholder: '请输入合同名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'nvc',
            type: 'input',
            templateOptions: {
              label: '公司名称',
              placeholder: '请输入公司名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'hgj',
            type: 'input',
            templateOptions: {
              label: '部门名称',
              placeholder: '请输入部门名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'qw',
            type: 'date',
            templateOptions: {
              label: '开始时间',
              placeholder: '结束时间',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }


        ]
      },
      {
        col: 12,
        id: "c",
        type: "panel",
        title: "供应商信息",
        genre: "form",
        fields: [
          {
            key: 'avc',
            type: 'input',
            templateOptions: {
              label: '公司代码',
              placeholder: '请输入合同名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'nvc',
            type: 'input',
            templateOptions: {
              label: '公司名称',
              placeholder: '请输入公司名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'hgj',
            type: 'input',
            templateOptions: {
              label: '部门名称',
              placeholder: '请输入部门名称',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }, {
            key: 'pic',
            type: 'file',
            templateOptions: {
              label: '图片',
              placeholder: '图片上传',
              required: true,
              divCol: 24,
              lblCol: 4,
              inputCol: 20
            }
          }


        ]
      }
    ]
  };
    data = {
        renderData: [
            {
                col: 24,
                type: "tabs",
                title: "动态表单区域一",
                tabs: [
                    {
                        id: "a",
                        title: "操作日志一",
                        genre: "form",
                        fields: this.feild1
                    },
                    {
                        id: "b",
                        title: "操作日志二",
                        genre: "group",
                        fields: this.data1
                    }
                ]
            }
        ]
    };

    values=[];

    dataArray = [this.data, this.data1];



    submit() {
        this.form.patchValue({name: "abc"});


        console.log(this.form);
        alert(JSON.stringify(this.model));
    }

    getTabChange($event: any) {

    }
  private _current = 0;
  private _pages = 0;
  private _searchText = '';
  contractLoading =false;
  contract$: Observable<any[]>;
  itemsData:any;
  contractinput$ = new Subject<string>();

  private loadContract() {
    this.contract$ = concat(
      of([]), // default items
      this.contractinput$.pipe(
        debounceTime(500),
        distinctUntilChanged(),
        tap(() => this.contractLoading = true),
        switchMap((term) => {
          if (missing(term)) {
            this.contractLoading = false;
            return of([]);
          }
          const data = {page: 0, size: 10,key:term};
          return this.apiService.post("acc.contract.find", data).pipe(
           map((res) =>{
                this.itemsData=[];
                this._searchText = term;
                this.itemsData = this.itemsData.concat(res.content);
                this._current = res.page + 1;
                this._pages = res.pages;
                return res.content
             }
           ),
           catchError(() => of([])), // empty list on error
           tap(() => this.contractLoading = false)
        )})
      )
    );
  }


  fetchMore() {
    this.contractLoading = true;
    // using timeout here to simulate backend API delay
    if (this._current === this._pages || this._searchText == '') {
      this.contractLoading = false;
      return;
    }
    const data = {key: this._searchText, page: this._current, size: 10};
    this.apiService.post("acc.contract.find", data).subscribe(item => {
      this.contractLoading = false;
      if (item.page === 0) {
        this.itemsData = [];
      }
      this.itemsData = this.itemsData.concat(item.content);
      this.contract$ = of(this.itemsData);
      this._current = item.page + 1;
      this._pages = item.pages;
    });

  }


    testApi(){
      let area={};
      this.cityService.getChildren('460000').subscribe(x=>console.log(x));

    }

    ngAfterViewInit() {
        console.log(this.form);
    }

}
